const fs = require('fs')

/**
 * promise封装
 */
const readFilePromse = fileUrl => {
	// 使用promise封装异步读文件操作
	const promise = new Promise(function (resolve, reject) {
		//封装异步读文件
		fs.readFile(fileUrl, 'utf-8', function (err, data) {
			if (err) {
				reject('读文件出错')
				return
			}
			resolve(data.toString())
		})
	})

	return promise
}

const writeFilePromse = (fileur2, content) => {
	const promise = new Promise(function (resolve, reject) {
		// 2异步写文件
		fs.writeFile(fileur2, content, 'utf-8', function (err, data) {
			if (err) {
				reject('写文件出错')
				return
			}
			resolve('写文件成功')
		})
	})
	return promise
}

/**
 * 复制文件
 *   old.txt -> new.txt
 */
const copyFile = (oldFile, newFile) => {
	readFilePromse(oldFile)
		.then(data => {
			writeFilePromse(newFile, data)
				.then(data => console.log(data))
				.catch(err => console.log(err))
		})
		.catch(err => {
			console.log(err)
		})
}

module.exports = {
	readFilePromse,
	writeFilePromse,
	copyFile,
}
